/**
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
** \file TreeAttribute.cpp
** \version $Id: TreeAttribute.cpp 24 2009-10-28 05:30:51Z rigdern $
*/

#include "TreeAttribute.h"
#include <stdexcept>

TreeAttribute::TreeAttribute(std::string columnName)
  : BasicAttribute(columnName),
    _root(NULL),
    _height(0)
{}

TreeAttribute::~TreeAttribute()
{
  std::map<std::string, Node*>::iterator it;
  
  for (it = _nodeMap.begin(); it != _nodeMap.end(); ++it)
    delete it->second;
  
  _nodeMap.clear();
}

TreeAttribute::Node*
TreeAttribute::addNode(const std::string& nodeName, Node* parent)
{
  Node* newNode = NULL;
  
  if (parent) {
    newNode = new Node(nodeName, parent);
    _height = std::max(_height, newNode->depth);
  } else if (_root) {
    _nodeMap.erase(nodeName);
    _root->name = nodeName;
    newNode = _root;
  } else {
    _root = new Node(nodeName, NULL);
    _height = _root->depth;
    newNode = _root;
  }
  _nodeMap[nodeName] = newNode;
  
  return newNode;
}

unsigned int
TreeAttribute::height() const
{
  return _height;
}

void
TreeAttribute::generalizeString(std::string& value, unsigned int level)
{
  Node* node;
  
  node = _nodeMap[value];
  while (node && level-- > 0) {
    node = node->parent;
  }
  
  if (!node)
    throw std::invalid_argument("Invalid value or level for generalization of a tree attribute.");
  else
    value = node->name;
}